package com.eques.demo.bind

import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.net.wifi.WifiManager
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import com.alibaba.fastjson.JSONObject
import com.eques.base.BaseActivity
import com.eques.demo.R
import com.eques.util.Config
import com.eques.util.NetConnctioUtils.PERMISSION_REQUEST_CODE
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.OutputStream
import java.net.Socket
import java.util.concurrent.Executors

class HostActivity : BaseActivity() {
    private lateinit var btnConfirm: Button
    private lateinit var btnSystemSettings: Button
    private lateinit var tvStatus: TextView
    private lateinit var etWifiName: EditText
    private lateinit var etWifiPassword: EditText

    // 配置参数
    private val deviceIp = "192.168.4.1"   // 修改为目标设备IP
    private val devicePort = 10001            // 修改为目标设备端口
    private val targetSsidPrefix = "CloudHome"   // 目标WiFi前缀

    // Socket连接
    private var socket: Socket? = null
    private var outputStream: OutputStream? = null
    private var isConnected = false

    // 线程池
    private val ioExecutor = Executors.newSingleThreadExecutor()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_host)
        initView()
        initData()

    }


    /** 检查权限 */
    private fun checkPermissions() {
        val permissions = arrayOf(
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION
        )
        val permissionList = permissions.filter {
            checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED
        }
        if (permissionList.isNotEmpty()) {
            ActivityCompat.requestPermissions(
                this,
                permissionList.toTypedArray(),
                PERMISSION_REQUEST_CODE
            )
        }
    }

    /** 检查当前网络是否符合条件 */
    private fun checkNetworkAndConnect() {
        if (!isWifiConnected()) {
            runOnUiThread {
                Toast.makeText(this, "请先连接到WiFi", Toast.LENGTH_LONG).show()
            }
            return
        }

        val ssid = getCurrentSsid()
        if (ssid == null) {
            runOnUiThread {
                Toast.makeText(this, "无法获取SSID，请检查权限或WiFi设置", Toast.LENGTH_LONG).show()
            }
            return
        }

        if (ssid.startsWith(targetSsidPrefix, ignoreCase = true)) {
            connectToDevice()
        } else {
            etWifiName.setText(ssid)
        }
    }

    /** 获取当前连接的SSID */
    private fun getCurrentSsid(): String? {
        val wifiManager = applicationContext.getSystemService(Context.WIFI_SERVICE) as? WifiManager
        if (wifiManager == null) {
            return null
        }

        val connectionInfo = wifiManager.connectionInfo ?: return null

        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            // Android 10+需要位置权限
            if (ActivityCompat.checkSelfPermission(
                    this,
                    Manifest.permission.ACCESS_FINE_LOCATION
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                return null
            }
            connectionInfo.ssid?.removeSurrounding("\"")
        } else {
            @Suppress("DEPRECATION")
            connectionInfo.ssid?.removeSurrounding("\"")
        }
    }

    /** 连接设备 */
    private fun connectToDevice() = ioExecutor.execute {
        if (isConnected) return@execute

        try {
            socket = Socket(deviceIp, devicePort)
            outputStream = socket?.getOutputStream()
            isConnected = true

            runOnUiThread {
                btnConfirm.isEnabled = true
                tvStatus.text = "已连接设备: ${socket?.remoteSocketAddress}"
                Toast.makeText(this, "设备连接成功", Toast.LENGTH_SHORT).show()
            }
        } catch (e: Exception) {
            e.printStackTrace()
            runOnUiThread {
                Toast.makeText(this, "连接失败: ${e.message}", Toast.LENGTH_LONG).show()
            }
        }
    }

    /** 断开连接 */
    private fun disconnectSocket() = ioExecutor.execute {
        try {
            socket?.close()
            outputStream?.close()
            isConnected = false
            runOnUiThread {
                btnConfirm.isEnabled = false
                tvStatus.text = "连接已断开"
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /** 初始化点击事件 */
    private fun setupClickListeners() {
        // 跳转系统设置
        btnSystemSettings.setOnClickListener {
            startActivity(Intent(Settings.ACTION_WIFI_SETTINGS))
        }

        // 发送配置数据
        btnConfirm.setOnClickListener {
            sendDeviceConfig()
        }
    }

    /** 发送设备配置 */
    private fun sendDeviceConfig() = CoroutineScope(Dispatchers.IO).launch {
        if (!isConnected) {
            showToast("请先连接设备")
            return@launch
        }

        val wifiName = etWifiName.text.toString().trim()
        val wifiPass = etWifiPassword.text.toString().trim()

        if (wifiName.isEmpty() || wifiPass.isEmpty()) {
            showToast("请输入完整的WiFi信息")
            return@launch
        }

        try {
            // 构建JSON数据
            val jsonData = JSONObject().apply {
                put("ssid", wifiName)
                put("pwd", wifiPass)
                put("user_name", preference.getString(Config.EQUES_USER_KEY))
            }

            // 发送数据
            outputStream?.write(jsonData.toString().toByteArray())
            outputStream?.flush()

            showToast("配置发送成功")
        } catch (e: Exception) {
            e.printStackTrace()
            showToast("发送失败: ${e.message}")
            disconnectSocket()
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        // 释放资源
        disconnectSocket()
    }

    override fun initView() {
        btnConfirm = findViewById(R.id.btnConfirm)
        btnSystemSettings = findViewById(R.id.btnSystemSettings)
        tvStatus = findViewById(R.id.tvStatus)
        etWifiName = findViewById(R.id.etWifiName)
        etWifiPassword = findViewById(R.id.etWifiPassword)
    }

    override fun initData() {
        checkPermissions()
        setupClickListeners()
    }

    /** 处理权限请求结果 */
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)

        if (requestCode != PERMISSION_REQUEST_CODE) {
            return
        }

        if (areAllPermissionsGranted(permissions, grantResults)) {
            checkNetworkAndConnect()
        } else {
            Toast.makeText(this, "需要位置权限获取WiFi信息", Toast.LENGTH_LONG).show()
        }
    }

    override fun onResume() {
        super.onResume()
        checkNetworkAndConnect()
    }

    /**
     * 检查所有权限是否都被授予
     * @param permissions 请求的权限列表
     * @param grantResults 权限请求的结果
     * @return 如果所有权限都被授予则返回 true，否则返回 false
     */
    private fun areAllPermissionsGranted(
        permissions: Array<String>,
        grantResults: IntArray
    ): Boolean {
        if (permissions.size != grantResults.size) {
            // 权限和结果数量不一致，视为未授权
            return false
        }

        for (i in grantResults.indices) {
            if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                return false
            }
        }
        return true
    }

    /**
     * 检查是否连接到WiFi
     * @return 如果连接到WiFi则返回 true，否则返回 false
     */
    private fun isWifiConnected(): Boolean {
        val connectivityManager =
            getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
        if (connectivityManager == null) {
            return false
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val network = connectivityManager.activeNetwork
            val capabilities = connectivityManager.getNetworkCapabilities(network)
            return capabilities?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) == true
        } else {
            @Suppress("DEPRECATION")
            val networkInfo = connectivityManager.activeNetworkInfo
            return networkInfo?.type == ConnectivityManager.TYPE_WIFI
        }
    }
}
